package com.luke.star.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpUtils;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.luke.star.bean.WxSendTempReq;
import com.luke.star.bean.WxSignatureReq;
import com.luke.star.bean.constant.WeiXinFinalValue;
import com.luke.star.bean.enums.ContentTypeEnum;
import com.luke.star.util.HTTPUtils;
import com.luke.star.util.WeiXinMassageKit;
import com.luke.star.util.WeiXinSecurityKit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class WeixinConfigController {
	
	private boolean checkSign(WxSignatureReq req) {
		if(StringUtils.isEmpty(req.getTimestamp()) || StringUtils.isEmpty(req.getNonce()) || StringUtils.isEmpty(req.getEchostr())) {
			return false;
		}
		
		String[] arrys = {WeiXinFinalValue.TOKEN,req.getTimestamp(), req.getNonce()};
		Arrays.sort(arrys);
		StringBuffer buffer=new StringBuffer();
		for(String arr:arrys){
			buffer.append(arr);
		}
		
		try {
			String shalMsg=WeiXinSecurityKit.shal(buffer.toString());
			if(shalMsg.equals(req.getSignature())) {
				return true;
			}
		} catch (Exception e) {
			log.error("签名失败,",e);
		}
		return false;
	}
	
	private String weiXinEventProcessin(Map<String,Object> messageMap) throws Exception {
 		String msgType = (String) messageMap.get("MsgType");
 		log.info("请求的消息类型,MsgType:{}",msgType);
		if (WeiXinFinalValue.MSG_EVENT_TYPE.equals(msgType)) {
			//click类型 或者view类型
		} else if (WeiXinFinalValue.MSG_TEXT_TYPE.equals(msgType)) {
			// 文本类型
			return WeiXinMassageKit.textTypeHandler(messageMap);
		} else if (WeiXinFinalValue.MSG_IMAGE_TYPE.equals(msgType)) {
			// 如果是圖片消息
		}else if(WeiXinFinalValue.MSG_VOICE_TYPE.equals(msgType)){
			//语音
		}else if(WeiXinFinalValue.MSG_SHORTVIDEO_TYPE.equals(msgType)){
			//短视频
		}else if(WeiXinFinalValue.MSG_VIDEO_TYPE.equals(msgType)){
		}else if(WeiXinFinalValue.MSG_LOCATION_TYPE.equals(msgType)){
		}
		return "success"; 		
	}

	/**
	 * 微信配置入口
	 * @param request
	 * @param response
	 * @param head
	 */
	//,produces = "text/html;charset=UTF-8"
	@RequestMapping(value="/weixin/wxCfgEntrance")
	public void wxCfgEntrance(HttpServletRequest request, HttpServletResponse response,WxSignatureReq head) {
		response.setCharacterEncoding("UTF-8");
		log.info("微信请求数据head：{}",head.toString());
		try {
			if(checkSign(head)) {
				log.info("入口配置设置响应 res:{}",head.getEchostr());
				response.setContentType(ContentTypeEnum.jsonutf8.code);
				response.getWriter().write(head.getEchostr());
				return;
			}
			
			Map<String, Object> messageMap=null;
			if("aes".equals(head.getEncrypt_type())) {
				log.info("aes加密传输的消息,开始解析------");
				messageMap = WeiXinMassageKit.handlerProcessEncryptionMessage(request,head);
			}else {
				log.info("明文传输的消息,开始解析------");
				messageMap = WeiXinMassageKit.handlerProcessProclaimedMessage(request);
				
			}
			
			String resmsg = weiXinEventProcessin(messageMap);
			
			log.info("响应微信请求res：{}",resmsg);
			response.setContentType(ContentTypeEnum.xmlutf8.code);
			response.getWriter().write(resmsg);

			//TODO 1.每日通知的制作,使用模板消息
			//TODO OPENID存储，access_tonken存储
			//TODO 2.组织数据
			//TODO 4. 其他的拦截器作用
			//TODO 3.做菜单
		} catch (Exception e) {
			log.error("微信请求信息异常，",e);
			try {
				response.setContentType(ContentTypeEnum.jsonutf8.code);
				response.getWriter().write("{errorMsg:\"请求报文错误\"}");
			} catch (IOException e1) {
				log.error("微信响应错误信息异常，",e1);
			}
		}
	}
	
	//获取access_token
	public static String getAccessToken() {
		try {
			String url=WeiXinFinalValue.GET_ACCESSTOKEN;
			url=url.replace("APPID", WeiXinFinalValue.APPID).replace("APPSECRET1", WeiXinFinalValue.APPSECRET);
//			url=url.replace("APPID", WeiXinFinalValue.APPID).replace("APPSECRET", WeiXinFinalValue.APPSECRET);
			String res = HTTPUtils.doGetUtf8(url);
			System.out.println("获取access_token响应:"+res);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		return null;
	}
	//发送模板
	public static void sendTempMsg() {
		//10:20~12:20
		try {
			String accessToken = "20_7FJdYWBKo1pl7AAfdBADgmo74K4H8UdKZkAJoxPSBKBLRqRnSTBC7LaoZ_UoDv9BPmxM3Pb5jGnR-0Dlzsk6mMGA-vtn8mW4mph3E0oMNb1ZDIxfegXJTXK9Djh1PWchGCoeJ8IOQM-HFkA_QMFiAEAIEX";
			String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
			String reqstr = "      {" + 
					"           \"touser\":\"oGHLM5tBQGuFuxOezSZhTBkacU5s\"," + 
					"           \"template_id\":\"qPn9tKfj0RbiO0h1zHXJAC-QjP-HjNlKtRqGVPeaaws\"," + 
					"           \"data\":{" + 
					"                   \"taskTime\": {" + 
					"                       \"value\":\"2019.04.05 周五\"," + 
					"                       \"color\":\"#173177\"" + 
					"                   }," + 
					"                   \"taskInfo\":{" + 
					"                       \"value\":\"7:00早起 +1(22%)；录歌1首 +5(37%)；\"," + 
					"                       \"color\":\"#173177\"" + 
					"                   }" + 
					"           }" + 
					"       }";
			String res = HTTPUtils.doPostJsonutf8(url, reqstr);
			System.out.println("模板消息响应res："+res);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	public static void main(String[] args) {
		getAccessToken();
	}
	
	
}
